package com.studyroom.service.impl;

import cn.hutool.json.JSONUtil;
import com.studyroom.dto.Mail;
import com.studyroom.dto.Result;
import com.studyroom.dto.UserDTO;
import com.studyroom.entity.User;
import com.studyroom.service.MailService;
import com.studyroom.utils.CacheClient;
import com.studyroom.utils.UserHolder;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

import static com.studyroom.utils.RabbitMqContants.EXCHANGE_TOPIC;
import static com.studyroom.utils.RedisContants.MAIL_KEY;

@Service
public class MailServiceImpl implements MailService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AmqpTemplate amqpTemplate;

    @Override
    public Result receive() {
        UserDTO me= UserHolder.getUser ();
        String mailKey=MAIL_KEY+me.getId ();
        List<String> mailJsonList=stringRedisTemplate.opsForList ().range (mailKey,0,-1);
        List<Mail> mailList=new LinkedList<> ();
        for(String mailJson:mailJsonList) {
            mailList.add (JSONUtil.toBean (mailJson, Mail.class));
        }
        return Result.ok (mailList);
    }
    public Result send(Mail mail){
        String mailJson=JSONUtil.toJsonStr (mail);
        amqpTemplate.convertAndSend (EXCHANGE_TOPIC,"mail",mailJson.getBytes(StandardCharsets.UTF_8));
        return Result.ok ();
    }

    @Override
    public Result clear() {
        UserDTO me=UserHolder.getUser ();
        String mailKey=MAIL_KEY+me.getId ();
        stringRedisTemplate.delete (mailKey);
        return Result.ok ();
    }
}
